import { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Modal, Popconfirm, message, Tag } from 'antd';
import { FileOutlined, FileImageOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getFileList, deleteFile } from '@/services/file/api';
import FileAdd from './FileAdd';
import FileAddImage from './FileAddImage';
import { RefreshFileStatus, DownloadFile } from '@/services/upload';
import styles from '@/pages/style.less';

export default () => {
  const tableRef = useRef<ActionType>();
  const [modalAddVisible, setModalAddVisible] = useState(false);
  const [modalImageVisible, setModalImageVisible] = useState(false);
  const [selectedRowId, setSelectedRowId] = useState('');

  const getRowClassName = (rd: API.FileItem) => {
    if ((rd.id as string) === selectedRowId) return styles.selectedRow;
    return '';
  };

  const columns: ProColumns<API.FileItem>[] = [
    {
      title: '文件名称',
      dataIndex: 'filename',
      render: (_, rd) => (
        <Button onClick={() => DownloadFile(rd.id as string, rd.filename as string)} type="link">
          {rd.filename}
        </Button>
      ),
    },
    {
      title: '文件路径',
      dataIndex: 'filepath',
    },
    {
      title: '文件是否存在',
      dataIndex: 'status',
      render: (_, rd) =>
        rd.status === 0 ? <Tag color="red">不存在</Tag> : <Tag color="green">存在</Tag>,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, rd) => [
        <Button
          type="primary"
          size="small"
          key="edit"
          onClick={async () => {
            await RefreshFileStatus(rd.id as string);
            tableRef.current?.reload();
            setSelectedRowId(rd.id as string);
          }}
        >
          刷新状态
        </Button>,
        <Popconfirm
          placement="topRight"
          title="是否删除?"
          okText="Yes"
          cancelText="No"
          key="delete"
          onConfirm={async () => {
            const response = await deleteFile(rd.id as string);

            if (response.code === 10000) message.info(`文件: 【${rd.filename}】 删除成功`);
            else message.warn(`文件: 【${rd.filename}】 删除失败`);

            tableRef.current?.reload();
          }}
        >
          <Button danger size="small">
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const addItem = async (values: any) => {
    console.log(values);
    setModalAddVisible(false);
    setModalImageVisible(false);
    tableRef.current?.reload();
    if (values && values.file && values.file.length > 0) setSelectedRowId(values.file[0].fid);
  };

  return (
    <PageContainer fixedHeader header={{ title: '文件列表' }}>
      <ProTable<API.FileItem>
        rowClassName={getRowClassName}
        columns={columns}
        rowKey="id"
        actionRef={tableRef}
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<FileOutlined />}
            type="primary"
            onClick={() => {
              setModalAddVisible(true);
            }}
          >
            上传文件
          </Button>,
          <Button
            key="button"
            icon={<FileImageOutlined />}
            type="primary"
            onClick={() => {
              setModalImageVisible(true);
            }}
          >
            上传图片
          </Button>,
        ]}
        request={async (params: API.FileItem & API.PageInfo) => {
          const resp = await getFileList(params);
          console.log(resp);
          return {
            data: resp.data.illuminant_file,
            total: resp.data.illuminant_file_aggregate.aggregate.count,
          };
        }}
      />
      <Modal
        destroyOnClose
        title="新增文件"
        visible={modalAddVisible}
        footer={null}
        onCancel={() => {
          tableRef.current?.reload();
          setModalAddVisible(false);
        }}
      >
        <FileAdd onFinish={addItem} />
      </Modal>
      <Modal
        destroyOnClose
        title="新增图片"
        visible={modalImageVisible}
        footer={null}
        onCancel={() => {
          tableRef.current?.reload();
          setModalImageVisible(false);
        }}
      >
        <FileAddImage onFinish={addItem} />
      </Modal>
    </PageContainer>
  );
};
